# encoding: utf-8

"""
一般仅作开发过程中测试之用。比如从一个文本文件导入音乐家基本信息，从一个目录导入音乐家的照片。
网站上线时，当然也是可以使用这个办法创建出一些初始的数据，但主要是为了开发过程中测试的方便。
VeryClassical的数据并非只有“管理员”才有权限增删查改。一般用户也有权限，但是可能会对不同
级别的用户做适当的限制。
"""

import os
import StringIO
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from model.music import Musician, Photo


def get_id_from_full_name(full_name):
    return full_name.lower().replace(' ', '_')

# 格式：
#   UNAME|原名|完整原名（first, middle, last）|译名|完整译名|yyyymmdd-[yyyymmdd]|国家|时期|头衔
def parse_musician_line_data(line):
    if line.startswith(u'#') or len(line) == 0:
        return None
    parts = line.split('|')
    if len(parts) != 9:
        return None
    if len(parts[0]) == 0: # no uid
        parts[0] = get_id_from_full_name(parts[2])
    return parts

# [Test] /admin/musician/import
# Import from /static/data/musician.txt.
class MusicianImportHandler(webapp.RequestHandler):
    def get(self):
        # A form to select the musician data file.
        path = os.path.join(os.path.dirname(__file__),
                            'template/admin_musician_import.html')
        self.response.out.write(template.render(path, {}))

    def post(self):
        musician_file_buffer = self.request.get("musician_file")
        musician_file = StringIO.StringIO(musician_file_buffer)
        for line in musician_file:
            musician_data = parse_musician_line_data(line.rstrip('\r\n'))
            if not musician_data:
                continue

            uname, name, name_full, name_tr, name_full_tr, date, country, era,\
                status = musician_data
            m = Musician(key_name=uname)
            m.name = name
            m.name_full = name_full
            m.name_tr = name_tr
            m.name_full_tr = name_full_tr
            m.date = date
            m.country = country
            m.era = era
            m.status = status
            m.put()

        self.redirect('/musician')


# [Test] /admin/musician/photo_import
# Import from /static/data/musician_photo_list.txt.
class MusicianPhotoImportHandler(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__),
                            'template/admin_musician_photo_import.html')
        self.response.out.write(template.render(path, {}))

    def post(self):
        photo_file_buffer = self.request.get("musician_photo_file")
        photo_file = StringIO.StringIO(photo_file_buffer)
        for line in photo_file:
            line = line.rstrip('\r\n')
            # 格式：UNAME:photo1|photo2|...
            uname, photo_urls = line.split(':')
            for photo_url in photo_urls.split('|'):
                p = Photo(url=photo_url,
                          musician_uname = uname)
                p.put()

        self.redirect('/musician')


application = webapp.WSGIApplication(
    [('/admin/musician/import', MusicianImportHandler),
     ('/admin/musician/photo_import', MusicianPhotoImportHandler),],
    debug = True)


def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()
